"use client";

import { motion } from "framer-motion";
import { BOARD_HEIGHT, BOARD_WIDTH, GameState, TETROMINOES, Tetromino, TetrominoType, getGhostPosition } from "@/lib/tetris";

interface TetrisBoardProps {
  board: (TetrominoType | null)[][];
  currentPiece: Tetromino;
  currentPosition: { x: number; y: number };
  gameOver: boolean;
  isPaused: boolean;
}

const TetrisBoard = ({
  board,
  currentPiece,
  currentPosition,
  gameOver,
  isPaused,
}: TetrisBoardProps) => {
  // 计算阴影位置（预览落地位置）
  const ghostPosition = getGhostPosition(board, currentPiece, currentPosition);

  // 渲染游戏板
  const renderBoard = () => {
    // 创建游戏板的副本
    const boardCopy = board.map(row => [...row]);
    
    // 添加当前方块的阴影（预览落地位置）
    for (let y = 0; y < currentPiece.shape.length; y++) {
      for (let x = 0; x < currentPiece.shape[y].length; x++) {
        if (currentPiece.shape[y][x]) {
          const boardY = ghostPosition.y + y;
          const boardX = ghostPosition.x + x;
          
          if (
            boardY >= 0 &&
            boardY < BOARD_HEIGHT &&
            boardX >= 0 &&
            boardX < BOARD_WIDTH &&
            boardCopy[boardY][boardX] === null
          ) {
            // 标记为阴影，但不覆盖已有的方块
            boardCopy[boardY][boardX] = 'ghost' as TetrominoType;
          }
        }
      }
    }
    
    // 添加当前方块
    for (let y = 0; y < currentPiece.shape.length; y++) {
      for (let x = 0; x < currentPiece.shape[y].length; x++) {
        if (currentPiece.shape[y][x]) {
          const boardY = currentPosition.y + y;
          const boardX = currentPosition.x + x;
          
          if (
            boardY >= 0 &&
            boardY < BOARD_HEIGHT &&
            boardX >= 0 &&
            boardX < BOARD_WIDTH
          ) {
            // 添加当前方块
            boardCopy[boardY][boardX] = currentPiece.type;
          }
        }
      }
    }
    
    return boardCopy;
  };

  const renderedBoard = renderBoard();

  return (
    <div className="relative w-full max-w-md mx-auto aspect-[1/2] rounded-md overflow-hidden border border-primary/30 shadow-lg shadow-purple-500/20 bg-gradient-to-b from-indigo-900/80 to-purple-900/80">
      {/* 游戏板网格 */}
      <div className="tetris-grid w-full h-full p-1 rounded-md">
        {renderedBoard.map((row, y) =>
          row.map((cell, x) => {
            // 确定单元格的颜色
            let cellColor = "bg-transparent";
            let borderColor = "border-indigo-900/30";
            let animationClass = "";
            
            if (cell === 'ghost') {
              cellColor = "bg-white/10";
              borderColor = "border-white/20";
            } else if (cell) {
              cellColor = TETROMINOES[cell].color;
              borderColor = "border-white/30";
              animationClass = "animate-pulse";
            }
            
            return (
              <motion.div
                key={`${y}-${x}`}
                className={`tetris-cell ${cellColor} border ${borderColor} ${animationClass}`}
                initial={{ opacity: cell ? 0 : 1, scale: cell ? 0.8 : 1 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ duration: 0.1 }}
                whileHover={{ scale: cell ? 1.05 : 1 }}
              />
            );
          })
        )}
      </div>
      
      {/* 游戏结束覆盖层 */}
      {gameOver && (
        <div className="absolute inset-0 bg-gradient-to-b from-red-900/80 to-black/80 flex flex-col items-center justify-center p-4 text-center">
          <motion.h2
            className="text-3xl font-bold text-red-400 mb-2 drop-shadow-glow"
            initial={{ y: -20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.2 }}
          >
            游戏结束
          </motion.h2>
          <motion.p
            className="text-white mb-4 text-lg"
            initial={{ y: -10, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.4 }}
          >
            按 R 键重新开始
          </motion.p>
        </div>
      )}
      
      {/* 暂停覆盖层 */}
      {isPaused && !gameOver && (
        <div className="absolute inset-0 bg-gradient-to-b from-blue-900/70 to-purple-900/70 backdrop-blur-sm flex items-center justify-center">
          <motion.h2
            className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent"
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ 
              repeat: Infinity, 
              repeatType: "reverse", 
              duration: 1.5 
            }}
          >
            已暂停
          </motion.h2>
        </div>
      )}
    </div>
  );
};

export default TetrisBoard;